import { useEffect } from "react";
import {
  NavLink,
  Outlet,
  useLoaderData,
  Form,
  useNavigation,
  redirect,
  useSubmit,
} from "react-router-dom";
import { getContacts, createContact } from "../contact";

export async function loader({ request }) {
  let url = new URL(request.url);
  const q = url.searchParams.get("q");
  const contact = await getContacts(q);
  return { contact, q };
}

export async function action() {
  const contact = await createContact();
  return redirect(`/contacts/${contact.id}/edit`);
}

export default function Root() {
  const { contact, q } = useLoaderData();
  const navigation = useNavigation();
  const submit = useSubmit();

  const search =
    navigation.location &&
    new URLSearchParams(navigation.location.search).has("q");

  useEffect(() => {
    document.getElementById("q").value = q;
  }, [q]);

  return (
    <>
      <div id="sidebar">
        <h1>React Router Contacts</h1>
        <div>
          <Form id="search-form" role="search">
            <input
              id="q"
              placeholder="Search"
              type="search"
              name="q"
              aria-label="Search contacts"
              defaultValue={q}
              onChange={(event) => {
                const isFirstSearch = q === null;
                submit(event.currentTarget.form, {
                  replace: !isFirstSearch,
                });
              }}
              className={search ? "loading" : ""}
            ></input>
            <div id="search-spinner" aria-hidden hidden={!search}>
              {" "}
            </div>
            <div className="sr-only" aria-live="polite"></div>
          </Form>
          <Form method="post">
            <button type="submit">New</button>
          </Form>
        </div>
        <nav>
          <ul>
            {contact.map((item, key) => {
              return (
                <li key={item.id}>
                  <NavLink
                    to={`contacts/${item.id}`}
                    className={({ isActive, isPending }) =>
                      isActive ? "active" : isPending ? "pending" : ""
                    }
                  >
                    {item.first || item.last ? (
                      <>
                        {item.first}
                        {item.last}
                      </>
                    ) : (
                      <i>No Name</i>
                    )}{" "}
                    {item.favorite && <span>*</span>}
                  </NavLink>
                </li>
              );
            })}
          </ul>
        </nav>
      </div>
      <div
        id="detail"
        className={navigation.state === "loading" ? "loading" : ""}
      >
        <Outlet></Outlet>
      </div>
    </>
  );
}
